//
//  FMPlayerTools.swift
//  FM
//
//  Created by x on 2017/9/30.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit
import AVFoundation

class FMPlayerTools: NSObject {
    
    /// 创建一个该对象的静态常量
    static let tools:FMPlayerTools = {
        let item = FMPlayerTools()
        
        return item
    }()
    
    /// 创建一个单利对象
    ///
    /// - Returns: <#return value description#>
    class func shareInstance() ->FMPlayerTools {
        return tools
    }
    
    
    /// 播放新的音频
    ///
    /// - Parameter url: 音频的url
    func playFM(url:URL) -> Void {
        
        //0.首先移除上一个播放的Itme上的KVO
        if player.currentItem != nil {
            removeObserverToPlayItem(playItem: player.currentItem!)
        }
        //1.创建item
        let playerItem = AVPlayerItem(url: url)
        
        //2给正在播放的item添加KVO
        addObserverToPlayerItem(playItem: playerItem)
        
        //3.设置播放item
        player.replaceCurrentItem(with: playerItem)
        
        //4.播放音频
        player.play()
    }
    
    /// 暂停FM
    func pauseFM()-> Void {
        player.pause()
    }
    
    /// 恢复播放
    func playerFM() -> Void {
        player.play()
    }
    
    /// 得到播放进度
    ///
    /// - Returns: <#return value description#>
    func getCurrentPlayingFMProgress() -> Float64 {
        
        return getCurrentPlayingTime()/getCurrentPlayingDuration()
    }
    
    /// 得到当前播放时间
    ///
    /// - Returns: <#return value description#>
    func getCurrentPlayingTime() -> Float64 {
        return CMTimeGetSeconds(player.currentTime())
    }
    
    /// 得到改FM的总时间
    ///
    /// - Returns: <#return value description#>
    func getCurrentPlayingDuration() -> Float64 {
        return CMTimeGetSeconds((player.currentItem?.duration)!)
    }
    
//    /// 监听音频播放完成
//    func playerItemDidPlayToEndTime() ->Void {
//        print("音频播放完成了.......")
//    }
    
    /// 增加一个KVO来监控属性变化
    ///
    /// - Parameter playItem: <#playItem description#>
    private func addObserverToPlayerItem(playItem:AVPlayerItem) -> Void {
        playItem.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)
    }
    
    private func removeObserverToPlayItem(playItem:AVPlayerItem) -> Void {
        playItem.removeObserver(self, forKeyPath: "status")
    }
    
    //MARK: -- 拉加载
    lazy var player:AVPlayer = AVPlayer()
}

//MARK: -- 使用KVO监测playItem的一些属性变化事件

/// 音频加载成功
let playItemLoadSuccess = "playItemLoadSuccess"

let playItemLoadFiled = "playItemLoadFiled"


extension FMPlayerTools {
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "status" {
            //取得状态变化的新的key
            let statues = change?[NSKeyValueChangeKey.newKey] as! Int
            switch statues {
            case AVPlayerStatus.readyToPlay.rawValue:
                print("音乐已近加载完毕.准备播放...");
                //1.音频加载成功通知
                NotificationCenter.default.post(name: NSNotification.Name.init(playItemLoadSuccess), object: nil)
                
            case AVPlayerStatus.unknown.rawValue:
                print("AVPlayerStatusUnknown...")
                
            case AVPlayerStatus.failed.rawValue:
                print("加载远程音乐失败...");
                //1.音频加载失败通知
                NotificationCenter.default.post(name: NSNotification.Name.init(playItemLoadFiled), object: nil)
                
            default:
                break
                
            }
        }
    }
}
